'use strict';

const Service = require('egg').Service;


class FeedBackService extends Service {
    /**
     * 查询列表
     *
     * @param {String} title @default null -公告名称
     * @param {Boolean} sort @default -1 -排序
     * @param {String} type @default null -是否已解决
     * @param {Number} page @default 1 -当前页
     * @param {Number} limit @default 10 -返回条数
     * @param {String} select @default null -要显示的key
     */
    async find({ title = '', sort = -1, page = 1, limit = 10 } = {}, select = null) {
        const { ctx } = this;
        const userpopulate = 'headImg role username name';
        let query = {}
        if (type) {
            query.type = type
        }
        const res = await ctx.model.FeedBack
            .find(query)
            .regex('title', new RegExp(title, 'i'))
            .sort({ createAt: sort })
            .skip((Number(page) - 1) * Number(limit))
            .limit(Number(limit))
            .populate('auth', userpopulate)
            .select(select);
        const count = await ctx.model.FeedBack.find().regex('title', new RegExp(title, 'i')).count();
        return {
            count,
            page,
            list: res
        };
    }

    /**
     * 新增
     *
     * @param {String} title - 标题
     * @param {String} content - 内容
     */
    async create({ title, content, email, phone, weixin, qq } = {}) {
        const { ctx } = this;
        return await ctx.model.FeedBack.create({
            title,
            content,
            email,
            phone,
            weixin,
            qq,
            auth: ctx.state.user._id
        });
    }

    /**
     * 设置为已解决
     *
     * @param {String} id -id
     * @param {Object} payload -修改条件
     */
    async update(id, type) {
        const { ctx } = this;
        const feedBack = await ctx.model.FeedBack.findById(id);
        if (!feedBack) {
            ctx.throw(404, '留言不存在或已被删除',{
                code:'feed_back_not'
            });
        }
        // 权限验证
        await ctx.powerValidate(feedBack.auth._id);

        payload.updateAt = Date.now();
        return await ctx.model.FeedBack.findByIdAndUpdate(id, { type });
    }

    /**
     * 删除
     *
     * @param {String} ids -id
     */
    async destroy(id) {
        const { ctx } = this;
        const feedBack = await ctx.model.FeedBack.findById(id);
        if (!feedBack) {
            ctx.throw(404, '留言不存在或已被删除', {
                code: 'message_not'
            });
        }
        // 权限验证
        await ctx.powerValidate();

        return await ctx.model.FeedBack.findByIdAndRemove(id);
    }
}

module.exports = FeedBackService;
